<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElSwitch,
  ElPagination,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage,
  ElRow,
  ElCol,
} from "element-plus";
import { Plus } from "@vben/icons";
import { onMounted, ref } from "vue";
import addEdit from "./addEdit.vue";
const roleName = ref("");
const status = ref("");
import { list, deleteId, edit } from "#/api/sys/role";
import { useDebounceFn } from "@vueuse/core";

const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const statusOptions = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "1",
    label: "正常",
  },
  {
    value: "0",
    label: "禁用",
  },
];

const spaceInput = (value: string) => {
  // 过滤空格
  roleName.value = value.replace(/\s+/g, "");
};

const search = async () => {
  const params = {
    roleName: roleName.value,
    status: status.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  const { data } = await list(params);
  if (data.records.length > 0) {
    data.records.map((item) => {
      item.status = item.status + "";
    });
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
};

const debouncedSearch = useDebounceFn(search, 500);

const resetForm = () => {
  roleName.value = "";
  status.value = "";
  currentPage.value = 1;
  search();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};
const editItem = (row) => {
  dialogVisible.value.editDialog(row);
};

const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除角色【${row.roleName}】吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              const data = await deleteId(row.id);
              if (data.code == 200) {
                ElMessage.success("删除成功");
                done();
              } else {
                instance.confirmButtonLoading = false;
                ElMessage.error(`删除失败: ${data.msg || "未知错误"}`);
                done();
              }
            } catch (error) {
              instance.confirmButtonLoading = false;
              ElMessage.error(`删除失败: ${error.msg || "未知错误"}`);
            }
          } else {
            done();
          }
        },
      }
    );
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.msg || "未知错误"}`);
      console.error("删除角色失败:", error);
    }
  }
};

const updateStatus = async (row) => {
  const newStatus = row.status == "1" ? "0" : "1";
  if (row.status == "0") {
    try {
      await ElMessageBox.confirm(
        "关闭角色会导致该角色下的所有账号无法登录，是否确认关闭？",
        "关闭确认",
        {
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }
      );
    } catch (error) {
      row.status = newStatus;
      return;
    }
  }

  const params = {
    id: row.id,
    status: row.status,
  };

  try {
    const data = await edit(params);
    if (data.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      row.status = newStatus;
      ElMessage({
        type: "error",
        message: "修改失败",
      });
    }
  } catch (error) {
    row.status = newStatus;
    ElMessage({
      type: "error",
      message: "修改失败",
    });
    console.error("状态修改失败:", error);
  }
};

const dialogVisible = ref();
const addItem = () => {
  dialogVisible.value.addDialog();
};

onMounted(() => {
  search();
});
</script>

<template>
  <div class="p-2 pageStyle">
    <div class="search">
      <ElRow>
        <ElCol :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
          <div class="searchForm">
            <div>
              <span>角色名称：</span>
              <ElInput
                v-model="roleName"
                style="width: 240px; margin-right: 16px"
                placeholder="请输入角色名称"
                clearable
                @input="spaceInput"
              />
            </div>
            <div class="searchBtn">
              <span>角色状态：</span>
              <ElSelect
                v-model="status"
                style="width: 180px"
                placeholder="请选择角色状态"
                @change="search()"
              >
                <ElOption
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </div>
            <div class="searchBtn">
              <ElButton
                type="primary"
                style="margin-left: 10px"
                @click="debouncedSearch"
                >查询</ElButton
              >
              <ElButton @click="resetForm()">重置</ElButton>
            </div>
          </div>
        </ElCol>
        <ElCol :xs="4" :sm="4" :md="4" :lg="4" :xl="4" class="searchCol">
          <ElButton type="primary" style="float: right" @click="addItem"
            >添加</ElButton
          >
        </ElCol>
      </ElRow>
    </div>
    <div class="tablePage">
      <div style="padding: 0 24px 0 16px">
        <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
          <ElTable.TableColumn
            prop="roleName"
            label="角色名称"
            align="center"
          />
          <ElTable.TableColumn prop="sort" label="排序" align="center" />
          <ElTable.TableColumn
            prop="createTime"
            label="创建时间"
            align="center"
          />
          <ElTable.TableColumn prop="status" label="状态" align="center">
            <template #default="scope">
              <ElSwitch
                v-model="scope.row.status"
                @click.native.prevent="scope.row.id !== 1 && updateStatus(scope.row)"
                style="
                  --el-switch-on-color: #2f69eb;
                  --el-switch-off-color: #c0c4cc;
                "
                active-value="1"
                inactive-value="0"
                :disabled="scope.row.id == 1"
              />
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editItem(scope.row)"
                :disabled="scope.row.id == 1"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="delItem(scope.row)"
                :disabled="scope.row.id == 1"
              >
                删除
              </el-button>
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
      <div class="pagination">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <addEdit ref="dialogVisible" @search="search"></addEdit>
  </div>
</template>
<style lang="css" scoped>
.search {
  padding: 16px 24px 20px 16px;
  background: #fff;
}

.tablePage {
  height: calc(100vh - 172px);
  overflow: scroll;
  background: #fff;
}

.el-table--fit {
  height: calc(100vh - 240px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 0px 16px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.searchForm {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.el-row {
  display: flex;
  place-content: center center;
}

@media (max-width: 950px) {
  .searchForm {
    flex-direction: column;
    align-items: flex-start;
  }

  .searchBtn {
    margin-top: 10px;
  }
}
</style>
